<template>
	<view class="container">
		<view class="header">
			<text>购物车</text>
			<text @tap="enterManage" v-if="!isManage">管理</text>
			<text @tap="completeManage" v-else class="complete-manage">退出管理</text>
		</view>
		<!-- 正常购物清单 -->
		<view class="normal-list" :style="{ border: hasSelected ? '1rpx solid #ff5a14' : '1rpx solid #fff' }">
			<view class="normal-item" v-for="(goods, index) in normalList" :key="index">
				<view class="normal-tag-wrapper" @tap="handleItemSelect(index)">
					<Selected :selected="goods.selected"></Selected>
				</view>
				<muqian-lazyLoad :src="goods.thumbnail" width="150rpx" height="150rpx"></muqian-lazyLoad>
				<!-- <image :src="baseUrl + goods.thumbnail" class="goods-image"></image> -->
				<view class="goods-info">
					<text class="goods-name">{{ goods.name }}</text>
					<text class="goods-spec">{{ goods.spec }}</text>
					<text class="goods-spec">{{ goods.styleInfo.styleName }}</text>
					<view class="goods-price">
						<text style="margin-right: 10rpx; font-size: 25rpx; color: #666666">¥</text>
						<text>{{ goods.price.toFixed(2) }}</text>
					</view>
				</view>
				<view class="purchase-num">
					<!-- 计数器 -->
					<view class="counter">
						<text class="iconfont icon-jianhao sub" @tap="handleSub(index)" :class="normalList[index].num == 1 ? 'disabled-sub' : ''"></text>
						<input class="num" type="number" v-model="goods.num" @blur="handleBlur(index)" auto-blur />
						<text class="iconfont icon-jiahao add" @tap="handleAdd(index)"></text>
					</view>
				</view>
			</view>
		</view>

		<view class="abnormal-list" v-if="abnormalNum > 0">
			<view class="abnormal-header">
				<text class="abnormal-num">暂不能下单商品{{ abnormalNum }}件</text>
				<text class="abnormal-clear" @tap="clearAbnormalCart">清空无货商品</text>
			</view>
			<view class="empty-list" v-if="emptyList.length !== 0">
				<view class="empty-item" v-for="(goods, index) in emptyList" :key="index">
					<view class="abnormal-tag-wrapper">
						<text class="abnormal-tag">售罄</text>
					</view>
					<muqian-lazyLoad :src="goods.thumbnail" width="150rpx" height="150rpx"></muqian-lazyLoad>
					<!-- <image :src="baseUrl + goods.thumbnail" class="goods-image"></image> -->
					<view class="goods-info">
						<text class="goods-name">{{ goods.name }}</text>
						<text class="goods-spec">{{ goods.spec }}</text>
						<view class="abnormal-desc">商品已售罄，等待补货</view>
					</view>
				</view>
			</view>
			<view class="off-shelf-list" v-if="offShelfList.length !== 0">
				<view class="off-shelf-item" v-for="(goods, index) in offShelfList" :key="index">
					<view class="abnormal-tag-wrapper">
						<text class="abnormal-tag">停售</text>
					</view>
					<muqian-lazyLoad :src="goods.thumbnail" width="150rpx" height="150rpx"></muqian-lazyLoad>
					<!-- <image :src="baseUrl + goods.thumbnail" class="goods-image"></image> -->
					<view class="goods-info">
						<text class="goods-name">{{ goods.name }}</text>
						<text class="goods-spec">{{ goods.spec }}</text>
						<view class="abnormal-desc">商品已下架，等待重新上架</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 正下方固定工具栏 -->
		<view style="height: 120rpx">
			<view class="purchase-tool">
				<view class="tool-one" @tap="handleAllSelect">
					<Selected :selected="isAllSelected"></Selected>
					<text>全选</text>
				</view>
				<view class="tool-two">
					<text style="font-size: 27rpx">商品合计：</text>
					<text style="padding: 0 5rpx; font-size: 26rpx; color: #ff5a14">¥</text>
					<text class="total-price">{{ totalPrice.toFixed(2) }}</text>
				</view>
				<view class="tool-three">
					<text class="remove-btn" v-if="isManage" @tap="removeCart">删除({{ totalNum }})</text>
					<text class="confirm-btn" @tap="gotoConfirmOrder" v-else>结算({{ totalNum }})</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { checkCart } from '@/api/goods';
import Selected from '@/components/selected';
import { mapState, mapActions } from 'vuex';
export default {
	components: {
		Selected
	},
	data() {
		return {
			// 可购物商品列表
			normalList: [],
			// 可购物车商品列表副本，用于删除
			normalCopyList: [],
			// 售完列表
			emptyList: [],
			// 下架商品列表
			offShelfList: [],
			// 管理控制
			isManage: false,
			shopId: uni.getStorageInfoSync('shopId')
		};
	},

	onShow() {
		this.getCartList();
	},
	computed: {
		...mapState('cart', ['cartList']),
		totalPrice() {
			let totalPrice = 0;
			this.normalList.forEach((item) => {
				if (item.selected) {
					totalPrice += item.price * item.num;
				}
			});
			return totalPrice;
		},
		totalNum() {
			let totalNum = 0;
			this.normalList.forEach((item) => {
				if (item.selected) {
					totalNum += Number(item.num);
				}
			});
			return totalNum;
		},
		abnormalNum() {
			return this.emptyList.length + this.offShelfList.length > 0 ? this.emptyList.length + this.offShelfList.length : 0;
		},
		isAllSelected() {
			let selected = true;
			this.normalList.forEach((item) => {
				if (!item.selected) {
					selected = false;
				}
			});
			return selected;
		},
		hasSelected() {
			let selected = false;
			this.normalList.forEach((item) => {
				if (item.selected) {
					selected = true;
				}
			});
			return selected;
		}
	},
	methods: {
		...mapActions('cart', ['serializeCart']),
		/**
		 * 辅助函数
		 */
		setAllItemFlag(selected) {
			this.normalList.forEach((item) => {
				item.selected = selected;
			});
		},

		/**
		 * 获得购物车数据列表
		 * 分类：正常，售罄，下架
		 */
		getCartList() {
			const specInfos = this.cartList.map((item) => item.specInfo);
			const goodsIds = this.cartList.map((item) => item.id);
			this.normalList = [];
			this.emptyList = [];
			this.offShelfList = [];
			if (specInfos.length > 0) {
				this.checkCart(specInfos, goodsIds);
			}
		},

		/**
		 * @param {Object} specInfos
		 * 检查购物车商品库存
		 */
		async checkCart(specInfos, goodsIds) {
			const checkList = (await checkCart(specInfos, goodsIds)).data;
			/**
			 * 待删除正常列表的商品下标
			 */
			let removeArr = [];
			for (let { specInfo, goodsId, status, stockNum,styleIds } of checkList) {
				let tempArr = [];
					// 一个库存id可能决定不同规格的多件商品
					let goodsList = this.cartList.filter((item) => item.specInfo == specInfo && item.id === goodsId);
					if (goodsList.length === 0) {
						continue;
					}

				for (let index in this.normalList) {
					if (this.normalList[index].specInfo === specInfo && this.normalList[index].id === goodsId) {
						tempArr.push(index);
					}
				}
				if (status === 2) {
					goodsList.forEach((goods) => (goods.isOffShelf = true));
					this.offShelfList.push(...goodsList);
					removeArr.push(...tempArr);
				} else if (stockNum === 0 || stockNum === undefined) {
					goodsList.forEach((goods) => (goods.isEmpty = true));
					this.emptyList.push(...goodsList);
					removeArr.push(...tempArr);
				} else {
					goodsList.forEach((goods) => {
						goods.isEmpty = false;
						goods.isOffShelf = false;
						goods.num = goods.num > stockNum ? stockNum : goods.num;
					});
					if (tempArr.length === 0) {
						this.normalList.push(...goodsList);
					}
				}
			}
			// 删除
			this.normalList = this.normalList.filter((item) => {
				for (let index of removeArr) {
					if (item === this.normalList[index]) {
						return false;
					}
				}
				return true;
			});
			// for (let goods of this.cartList) {
			// 	let { status, stockNum } = checkList.find((item) => item.specInfo === goods.specInfo);
			// 	if (status === 2) {
			// 		goods.isOffShelf = true;
			// 		this.offShelfList.push(goods);
			// 	} else if (stockNum === 0) {
			// 		goods.isEmpty = true;
			// 		this.emptyList.push(goods);
			// 	} else {
			// 		goods.isEmpty = false;
			// 		goods.isOffShelf = false;
			// 		goods.num = goods.num > stockNum ? stockNum : goods.num;
			// 		this.normalList.push(goods);
			// 	}
			// }
			this.serializeCart();
		},

		/**
		 * @param {Object} index
		 * 处理单选
		 */
		handleItemSelect(index) {
			this.normalList[index].selected = !this.normalList[index].selected;
			if (this.isManage) {
				return;
			}
			if (this.normalList[index].selected) {
				this.checkCart([this.normalList[index].specInfo], [this.normalList[index].id]);
			} else {
				this.serializeCart();
			}
		},
		/**
		 * 处理全选
		 */
		handleAllSelect() {
			// 让item集体取反，可以将isAllSelected计算出来
			if (this.isAllSelected) this.setAllItemFlag(false);
			else this.setAllItemFlag(true);
			if (this.isManage) {
				return;
			}
			if (this.isAllSelected) {
				this.checkCart(
					this.normalList.map((item) => item.specInfo),
					this.normalList.map((item) => item.id)
				);
			} else {
				this.serializeCart();
			}
		},
		/**
		 * @param {Object} index
		 * 数量减
		 */
		handleSub(index) {
			if (this.normalList[index].num == 1 || this.isManage) {
				return;
			}
			this.normalList[index].num--;
			this.serializeCart();
		},
		/**
		 * @param {Object} index
		 * 数量加
		 */
		handleAdd(index) {
			if (this.isManage) {
				return;
			}
			this.normalList[index].num++;
			if (this.normalList[index].selected) {
				this.checkCart([this.normalList[index].specInfo], [this.normalList[index].id]);
			} else {
				this.serializeCart();
			}
		},
		handleBlur(index) {
			this.checkCart([this.normalList[index].specInfo], [this.normalList[index].id]);
		},
		// 进入购物车管理
		enterManage() {
			this.isManage = true;

			// 深拷贝保存副本
			this.normalCopyList = JSON.parse(JSON.stringify(this.normalList));

			// 将选择置为false，进入管理
			this.setAllItemFlag(false);
		},
		// 完成管理
		completeManage() {
			this.isManage = false;
			console.log(this.normalCopyList);
			for (let normalGoods of this.normalList) {
				for (let cartGoods of this.normalCopyList) {
					if (normalGoods.id == cartGoods.id && normalGoods.spec == normalGoods.spec) {
						normalGoods.selected = cartGoods.selected;
						break;
					}
				}
			}
			this.serializeCart();
		},
		removeCart() {
			this.normalList = this.normalList.filter((item) => !item.selected);
			this.$store.dispatch('cart/updateCart', [...this.normalList, ...this.emptyList, ...this.offShelfList]);
		},
		clearAbnormalCart() {
			this.emptyList = [];
			this.offShelfList = [];
			this.$store.dispatch('cart/updateCart', this.normalList);
			this.serializeCart();
		},
		gotoConfirmOrder() {
			let goodsList = this.normalList.filter((goods) => goods.selected);
			if (goodsList.length > 0) {
				let URLcoursePay = encodeURIComponent(JSON.stringify(goodsList))
				uni.navigateTo({
					url: `/pages/order/confirm_order?goodsList=${URLcoursePay}`
				});
			}
		}
	}
};
</script>

<style scoped lang="less">
@theme-color: #ff5a14;

.container {
	padding: 30rpx 20rpx 30rpx 20rpx;
}

.header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	text-align: right;
	margin-bottom: 10rpx;
	font-size: 28rpx;
	color: #9c9999;

	.complete-manage {
		color: @theme-color;
	}
}

.normal-list,
.abnormal-list {
	display: flex;
	flex-direction: column;
	gap: 30rpx;
	padding: 30rpx 25rpx 30rpx 0;
	border-radius: 20rpx;
	background-color: #fff;
	.normal-item,
	.empty-item,
	.off-shelf-item {
		display: flex;
		flex-direction: row;
		position: relative;

		.goods-image {
			width: 150rpx;
			height: 150rpx;
		}

		.goods-info {
			display: flex;
			flex: 1;
			flex-direction: column;
			margin-left: 30rpx;
			position: relative;
			gap: 8rpx;

			.goods-name {
				font-size: 28rpx;
				font-weight: bold;
			}

			.goods-spec {
				color: #a69999;
				font-size: 25rpx;
			}

			.goods-price {
				position: absolute;
				left: 0;
				bottom: 0;
				color: @theme-color;
				font-size: 30rpx;
				font-weight: bold;
			}
		}

		.purchase-num {
			position: absolute;
			right: 0;
			bottom: 0;
		}
	}
}
.abnormal-list {
	border: 0;
	margin-top: 20rpx;
	.abnormal-header {
		display: flex;
		justify-content: space-between;
		padding-left: 25rpx;
		.abnormal-num {
			color: #999999;
			font-size: 25rpx;
		}
		.abnormal-clear {
			color: @theme-color;
			font-size: 25rpx;
		}
	}
	.abnormal-desc {
		position: absolute;
		left: 0;
		bottom: 0;
		font-size: 25rpx;
	}
}

.normal-tag-wrapper,
.abnormal-tag-wrapper {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	width: 70rpx;
	.abnormal-tag {
		background-color: #c1c1c1;
		color: #fff;
		font-size: 16rpx;
		padding: 5rpx 10rpx;
		border-radius: 100rpx;
	}
}

.empty-list,
.off-shelf-list {
	display: flex;
	flex-direction: column;
	gap: 30rpx;
}

// 底层工具栏
.purchase-tool {
	width: 100%;
	height: 120rpx;
	background-color: #fff;
	display: flex;
	position: fixed;
	left: 0;
	bottom: 0;
	padding: 0 20rpx;
	z-index: 10;

	.tool-one {
		flex: 2;
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.tool-two {
		flex: 3;
		display: flex;
		align-items: center;

		.total-price {
			color: @theme-color;
			font-size: 35rpx;
			font-weight: bold;
		}
	}

	.tool-three {
		flex: 2;
		display: flex;
		align-items: center;

		.confirm-btn,
		.remove-btn {
			padding: 18rpx 0;
			width: 100%;
			text-align: center;
			color: #fff;
			font-size: 30rpx;
			border-radius: 40rpx;
		}

		.confirm-btn {
			background-color: @theme-color;
		}

		.remove-btn {
			background-color: red;
		}
	}
}

.counter {
	display: flex;
	flex-direction: row;

	.num {
		padding: 0 20rpx;
		width: 80rpx;
		text-align: center;
	}

	.disabled-sub {
		opacity: 0.3;
	}

	.sub {
		color: @theme-color;
		// 9rpx的padding + 1rpx的border = add元素10rpx的padding
		padding: 9rpx;
		border: 1rpx solid @theme-color;
		border-radius: 50%;
		font-size: 30rpx;
		display: inline-block;
	}

	.add {
		color: #fff;
		background-color: @theme-color;
		padding: 10rpx;
		border-radius: 50%;
		font-size: 30rpx;
	}
}
</style>
